//
//  ViewController.swift
//  CALayer1
//
//  Created by 李煜 on 2024/7/3.
//

import UIKit

class ViewController: UIViewController, CALayerDelegate {
    //两种方式使用CALayer绘制,都必须调用layer.setNeedsDisplay才能触发绘制draw方法
    //1.通过delegate方式
    //2.子类化CALyer,重写draw(in context:)方法
    
//    方法一步骤
//    1.创建layer,添加,frame
//    2.设置delegate,调用setNeedsDisplay
//    3.重写draw(in:context)
    
    //MARK: - 方法一:delegate绘制
    var oneLayer: CALayer = CALayer()
    //MARK: - 方法二:自定义CALayer方式绘制
    var twoLayer: TwoLayer = TwoLayer()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        
        oneMedthod()
        twoMethod()
        
    }
    func oneMedthod() {
        // 1.创建并设置frame
        view.layer.addSublayer(oneLayer)
        //设置分辨率
        oneLayer.contentsScale = UIScreen.main.scale
        oneLayer.borderColor = UIColor.blue.cgColor
        oneLayer.borderWidth = 5.0
        
        // 2. delegate
        oneLayer.delegate = self
    }
    func twoMethod() {
        view.layer.addSublayer(twoLayer)
        twoLayer.contentsScale = UIScreen.main.scale
        twoLayer.borderColor = UIColor.gray.cgColor
        twoLayer.borderWidth = 5.0
    }
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        let wh = view.bounds.width - 80
        oneLayer.frame = CGRectMake(40, 100, wh,wh);
        twoLayer.frame = CGRectMake(40, oneLayer.frame.maxY, wh,wh);
    }
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        oneLayer.setNeedsDisplay()
        twoLayer.setNeedsDisplay()
    }

    //MARK: draw方法
    func draw(_ layer: CALayer, in ctx: CGContext) {
        //画笔颜色
        ctx.setStrokeColor(UIColor.red.cgColor)
        ctx.setLineWidth(5.0)
        //形状
        ctx.addEllipse(in: CGRectMake(5, 5, 100, 100))
        //绘制(描边)
        ctx.strokePath()
    }
}

//MARK: - 方法二:子类CALayer方式绘制
class TwoLayer: CALayer {
    override func draw(in ctx: CGContext) {
        ctx.setFillColor(UIColor.orange.cgColor)
        ctx.addEllipse(in: CGRectMake(10, 10, 100, 80))
        ctx.fillPath()
    }
}


#if DEBUG

import SwiftUI

struct ViewControllerRepresentable: UIViewControllerRepresentable {
    typealias UIViewControllerType = ViewController

    func makeUIViewController(context: Context) -> UIViewControllerType {
        ViewController()
    }
    
    func updateUIViewController(_ uiViewController: UIViewControllerType, context: Context) {
        
    }
}

struct ViewController_Previews: PreviewProvider {
    static var previews: some View {
        ViewControllerRepresentable()
    }
}

#endif
